<template>
  <el-form :inline="true" :model="ruleForm" class="demo-form-inline">
    <el-form-item label="客户">
      <el-select placeholder="请选择客户" clearable v-model="ruleForm.organId">
        <el-option v-for="customer in customers" :key="customer.id" :label="customer.supName" :value="customer.supId" />
      </el-select>
    </el-form-item>
    <el-form-item label="单据编号">
      <el-input v-model="ruleForm.number" placeholder="自动生成单据编号" readonly></el-input>
    </el-form-item>

    <el-form-item label="创建时间">
      <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>


    <div class="user-index-body-form-btn-item">
      <div class="ant-row-flex" style="display: flex; align-items: center;">
        <div class="ant-col" style="margin-right: 10px;">
          <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>

        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain>扫码录入</el-button>
        </div>
        <div class="ant-col" style="margin-right: 10px;">
          <el-button plain v-perm:sale:sale_order:insert:documents="insert">
            <el-icon style="margin-right: 5px;">
              <Clock />
            </el-icon>
            历史单据
          </el-button>
        </div>
        <div class="ant-col">
          <el-button plain>
            <el-icon style="margin-right: 5px;">
              <Grid />
            </el-icon>
            导入明细
          </el-button>
        </div>
      </div>

      <el-table :data="tableData" show-summary style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column width="120">
          <template #default="{ row }">

            <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
              v-perm:sale:sale_order:insert:Saleinorder="Saleinorder">
              <el-icon class="el-icon-left">
                <Plus />
              </el-icon>

            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="条码" width="120">
          <template #default="{ row }">
            <el-input v-model="row.barCode"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="名称" width="120">
          <template #default="{ row }">
            <el-input v-model="row.materialName"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="120">
          <template #default="{ row }">
            <el-input v-model="row.standard"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="库存" width="120">
          <template #default="{ row }">
            <el-input v-model="row.totalOperNumber"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.commodityUnit"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单价" width="120">
          <template #default="{ row }">
            <el-input v-model="row.wholesaledecimal" @input="updateRowCalculations(row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template #default="{ row }">
            <el-input v-model="row.operNumber" @input="updateRowCalculations(row)"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="金额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.allPrice" readonly></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税率" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxRate" @input="updateRowCalculations(row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="税额" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxMoney" readonly></el-input>
          </template>
        </el-table-column>
        <el-table-column label="价格合计" width="120">
          <template #default="{ row }">
            <el-input v-model="row.taxLastMoney" readonly></el-input>
          </template>
        </el-table-column>

        <el-table-column label="备注" width="100">
          <template #default="{ row }">
            <el-input v-model="row.totalOut"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="index-body tb">
      <el-form-item label="合计金额：" style="margin-right: 120px;">
        <el-input v-model="ruleForm.totalPrice" style="width: 185px">

        </el-input>
      </el-form-item>
      <el-form-item label="优惠率：" style="margin-right: 120px;">
        <el-input v-model="ruleForm.discountRate" style="width: 185px">

        </el-input>
      </el-form-item>
      <el-form-item label="收款优惠：" style="margin-right: 120px;">
        <el-input v-model="ruleForm.paymentDiscount" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="优惠后金额：">
        <el-input v-model="ruleForm.discountedAmount" style="width: 240px"></el-input>
      </el-form-item>
    </div>

    <div class="index-body zb">
      <el-form-item label="结算账户：" style="margin-right: 120px;">
        <el-select clearable style="width: 200px; " placeholder="请选择客户" v-model="ruleForm.accountId">
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
        </el-select>
      </el-form-item>
      <el-form-item label="收取定金：" style="margin-right: 100px;">
        <el-input style="width: 240px" v-model="ruleForm.deposit"></el-input>
      </el-form-item>
    </div>

    <div class="ant-coloery" style="margin-right: 10px;">
      <el-form-item label="附件：">
        <el-button plain>
          <el-icon style="margin-right: 10px;">
            <MessageBox />
          </el-icon>上传附件
        </el-button>
      </el-form-item>
    </div>
  </el-form>
  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%"
    style="margin-left: 350px;margin-top: 200px">
    <router-view @close="close" @saveSaleinorder="saveSaleinorder" :data="data"></router-view>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';


const visible = ref(false);
const title = ref("");
const data = ref({});
const ruleForm = ref({
  discountRate: 0, // 或者设置为其他初始值
  paymentDiscount: 0, // 或者设置为其他初始值
  discountedAmount: 0,
  number: '',
  totalPrice:'', // 或者设置为其他初始值
  // 其他属性...
});
const close = () => {
  visible.value = false;
};
// 表格数据
const tableData = ref([{
  barCode: '',
  categoryName: '',
  color: '',
  commodityUnit: '',
  materialName: '',
  mfrs: '',
  model: '',
  sku: '',
  standard: '',
  totalIn: '',
  totalOperNumber: '',
  totalOut: '',
  wholesaledecimal: 0, // 单价默认为0
  basicnumber: '',
  allPrice: 0, // 金额初始化为0
  taxRate: 0, // 默认税率为0
  taxMoney: 0, // 税额初始化为0
  taxLastMoney: 0 // 价格合计初始化为0
}]);

const Saleinorder = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}
const addRow = () => {
  tableData.value.push({
    barCode: '',
    categoryName: '',
    color: '',
    commodityUnit: '',
    materialName: '',
    mfrs: '',
    model: '',
    sku: '',
    standard: '',
    totalIn: '',
    totalOperNumber: '',
    totalOut: '',
    wholesaledecimal: '',
    basicnumber: '',
    allprice: '',
    taxLastMoney: ''
  });
};
const accounts = ref([]); // 存储结算账户数据
const loadAccounts = () => {
  request({
    url: '/basic/account/list',
    method: 'get'
  }).then(res => {

    accounts.value = res.data; // 更新结算账户数据
  }).catch(err => {
    console.error(err);
  });
};
loadAccounts();
const submitForm = () => {
  console.log('优惠率：', ruleForm.value.discountRate);
  console.log('收款优惠：', ruleForm.value.paymentDiscount);
  console.log('优惠后金额：', ruleForm.value.discountedAmount);
  // 基础数据准备
  const data = {
    erpDepotHead: {


      type: '其它',
      subType: '销售订单',
      number: ruleForm.value.number,
      organId: ruleForm.value.organId,
      creator: '1',
      accountId: ruleForm.value.accountId,
      changeAmount: ruleForm.value.deposit,
      totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0),
      discount: ruleForm.value.discountRate,
      discountMoney: ruleForm.value.paymentDiscount,
      discountLastMoney: ruleForm.value.discountedAmount,
      status: '0'
    },
    erpDepotItems: tableData.value.map(row => ({
      materialId: row.mid,
      materialExtendId: row.aid,
      materialUnit: row.commodityUnit,
      sku: row.sku,
      operNumber: row.operNumber,
      depotId: row.depotname,
      unitPrice: row.wholesaledecimal,
      allPrice: row.allPrice,
      remark: row.remark || '',
      taxRate: row.taxRate,
      taxMoney: row.taxMoney,
      taxLastMoney: row.taxLastMoney
    }))
  };

  // 添加请求
  request({
    url: '/sale/insert',
    method: 'post',
    data: data,
    headers: { 'Content-Type': 'application/json' }
  }).then(res => {
    console.log(res);
    console.log(addRow);

    ElMessage.success('提交成功');
  }).catch(err => {
    console.error(err);
    ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
  });
};



const updateRowCalculations = (row) => {
  // 金额 = 单价 * 数量
  const amount = row.wholesaledecimal * (row.operNumber || 1);
  row.allPrice = amount; // 设置金额

  // 税额 = 金额 * 税率
  row.taxMoney = amount * (row.taxRate / 100);

  // 价格合计 = 金额 - 税额
  row.taxLastMoney = amount - row.taxMoney;
};


const customers = ref([]);
const loadCustomers = () => {
  request({
    url: '/basic/vendor/list',
    method: 'get'
  }).then(res => {
    customers.value = res.data;
  }).catch(err => {
    console.error(err);
  });
};
loadCustomers();

// 页面加载时生成订单编号
onMounted(() => {
  // 从本地存储获取当前的订单编号，如果不存在则默认为1
  let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);

  // 自增
  currentOrderNumber++;

  // 格式化为10位数字并添加前缀
  const formattedOrderNumber = `XSDD${currentOrderNumber.toString().padStart(11, '0')}`;

  // 将生成的订单编号赋值到表单
  ruleForm.value.number = formattedOrderNumber;

  // 将新的订单编号存储到本地存储中，便于下次使用
  localStorage.setItem('orderNumber', currentOrderNumber.toString());
});



// 接收并显示保存的数据a
const saveSaleinorder = (selectedItems) => {
  tableData.value = selectedItems.map(item => ({
    barCode: item.barCode,
    categoryName: item.categoryName,
    color: item.color,
    commodityUnit: item.commodityUnit,
    materialName: item.materialName,
    mfrs: item.mfrs,
    model: item.model,
    sku: item.sku,
    standard: item.standard,
    totalIn: item.totalIn,
    totalOperNumber: item.totalOperNumber,
    totalOut: item.totalOut,
    wholesaledecimal: item.wholesaledecimal,
    basicnumber: item.basicnumber,
    allPrice: item.allprice,
    mid: item.mid,
    aid: item.aid,
    operNumber: 1, // 默认数量为1
    taxRate: 0, // 默认税率为0
    taxMoney: 0, // 默认税额为0
    taxLastMoney: 0 // 默认价格合计为0
  }));

  // 计算每一行的金额、税额和价格合计
  tableData.value.forEach(row => updateRowCalculations(row));
};



const insert = (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
};
</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
